package com.cn.springcloudwechat.service.personalcenter.serviceImpl;

import com.cn.springcloudwechat.common.utils.ErrorUtil;
import com.cn.springcloudwechat.mapper.mapper.YmPraiseMapper;
import com.cn.springcloudwechat.mapper.mapper.YmUserPointMapper;
import com.cn.springcloudwechat.model.YmUserPoint;
import com.cn.springcloudwechat.model.YmUserSignIn;
import com.cn.springcloudwechat.service.personalcenter.service.YmUserPointService;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * @Author Lg
 * @Date 2018/8/6 14:18
 * @Content
 */
@Service("YmUserPointService")
public class YmUserPointServiceImpl implements YmUserPointService{

    @Autowired
    YmUserPointMapper ymUserPointMapper;



    @Override
    public Integer insertUserPoint(Long userId,String changeDes,Integer changeType,String change) {
        Integer res = 0;
        YmUserPoint userPoint= ymUserPointMapper.getNewestPoint(userId);
        if(changeType != null){
            //查询是否获得过豆豆
            Integer result = ymUserPointMapper.getNumberOfPieces(changeType,userId);
            if(result == 0){
                YmUserPoint ymUserPoint = getPoint(userPoint,userId,changeDes,changeType,change);
                res = ymUserPointMapper.insertSelective(ymUserPoint);
            }
        } else {
            YmUserPoint ymUserPoint = getPoint(userPoint, userId, changeDes, changeType, change);
            res = ymUserPointMapper.insertSelective(ymUserPoint);
        }
        return res;
    }

    @Override
    public YmUserPoint getNewestPoint(Long userId) {
        Assert.notNull(userId,String.format(ErrorUtil.PARAMETER_NULL,"userId"));
        return ymUserPointMapper.getNewestPoint(userId);
    }

    public static YmUserPoint getPoint(YmUserPoint userPoint,Long userId,String changeDes,Integer changeType,String change){
        YmUserPoint ymUserPoint = new YmUserPoint();
        //获取豆豆
        Long changeBefore = 0L;
        if(userPoint != null){
            changeBefore = userPoint.getTotalPoint();
        }
        Long totalPoint = 0L;
        if(change.contains("+")){
            totalPoint = changeBefore + Long.valueOf(change.substring(1));
        }else {
            totalPoint = changeBefore - Long.valueOf(change.substring(1));
        }
        ymUserPoint.setChange(change);
        ymUserPoint.setTotalPoint(totalPoint);
        ymUserPoint.setChangeType(changeType);
        ymUserPoint.setChangeBefore(changeBefore);
        ymUserPoint.setUserId(userId);
        ymUserPoint.setChangeDes(changeDes);
        return ymUserPoint;
    }

}
